package danran.dbapi.controller.conf;

import com.alibaba.fastjson.JSONObject;
import danran.dbapi.common.ResponseDto;
import danran.dbapi.controller.util.JwtUtil;
import danran.dbapi.domain.User;
import danran.dbapi.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Classname JwtAuthInterceptor
 * @Description TODO
 * @Date 2022/1/17 17:24
 * @Created by RanCoder
 */
@Component
public class JwtAuthInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(JwtAuthInterceptor.class);
    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        log.info(request.getServletPath());
        // 跨域的预检请求直接放行
        if (request.getMethod().equals(HttpMethod.OPTIONS)) {
            return true;
        }

        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        PrintWriter writer = null;
        JSONObject rsp = new JSONObject();
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");

            String token = request.getHeader("Authorization");
            // 执行认证
            if (token == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                writer = response.getWriter();
//                writer.append("\"无token，请重新登录\"");
                rsp.put("msg", "无token，请重新登录");
                rsp.put("data", null);
                rsp.put("success", false);
                writer.append(rsp.toJSONString());
                return false;
            }

            // 获取 token 中的 userId
            String userId = JwtUtil.getAudience(token);
            log.info("userid = {}", userId);

            User user = userService.getUserById(Integer.valueOf(userId));
            if (user == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                writer = response.getWriter();
                rsp.put("msg", "用户不存在，请重新登录");
                rsp.put("data", null);
                rsp.put("success", false);
                writer.append(rsp.toJSONString());
                return false;
            }

            // 验证 token
            boolean b = JwtUtil.verifyToken(token, user.getPassword());
            if (b) {
                return true;
            } else {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                writer = response.getWriter();
                rsp.put("msg", "token无效，请重新登录");
                rsp.put("data", null);
                rsp.put("success", false);
                writer.append(rsp.toJSONString());
                return false;
            }
        } catch (Exception e) {
            log.warn(e.toString());
            writer = response.getWriter();
            writer.append(JSONObject.toJSONString(ResponseDto.fail("Token 非法")));
            return false;
        } finally {
            if (writer != null) {
                writer.close();
            }
        }

    }
}
